<template>
  <div class="login">
    <div class="logo">
      <img src="../assets/logo.png" alt="" />
    </div>
    <el-form
      class="login-content"
      :model="loginRuleForm"
      :rules="loginFormRule"
      ref="loginForm"
    >
      <el-form-item prop="username">
        <el-input
          v-model="loginRuleForm.username"
          prefix-icon="iconfont icon-user"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          type="password"
          v-model="loginRuleForm.password"
          prefix-icon="iconfont icon-lock_fill"
        ></el-input>
      </el-form-item>
    </el-form>
    <el-row>
      <el-button type="primary" plain @click="submit">登录</el-button>
      <el-button type="info" plain @click="reset">重置</el-button>
    </el-row>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 进行表单数据的绑定
      loginRuleForm: {
        username: "admin",
        password: "123456",
      },
      //表单验证的规则
      loginFormRule: {
        //用户名的验证规则
        username: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
        ],
        //密码验证规则
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //重置
    reset() {
      this.$refs.loginForm.resetFields();
    },
    //提交
    submit() {
      this.$refs.loginForm.validate(async (valid) => {
        //通过结构赋值获得data
        let { data: ref } = await this.$http.post("login", this.loginRuleForm);
        if (ref.meta.status !== 200) {
          this.$message.error("登录失败");
        } else {
          this.$message({
            message: "登录成功",
            type: "success",
          });
        }
        //1.将登陆成功后的token保存到sessionStorage中
        //项目中还有其他的api接口，必须在登录之后才能访问
        //token只因在当前网站打开期间生效，所以保存在sessionStorage
        console.log(ref.data.token);
        window.sessionStorage.setItem("token", ref.data.token);
        //2.成功登录后跳转到home页面
        this.$router.push("/home");
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.login {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 450px;
  height: 300px;
  border: 1px solid pink;
  border-radius: 10px;
  text-align: center;
  .el-row {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 40px;
  }
}
.logo {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 1px solid #808080;
  position: absolute;
  background: #fff;
  padding: 10px;
  box-sizing: border-box;
  left: 50%;
  transform: translate(-50%, -50%);
  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}
.login-content {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 100px;
  text-align: center;
  .el-input {
    width: 80%;
  }
}
</style>